package com.example.quartz.component;

import com.example.quartz.jobBean.TestJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class QuartzCustomComponent implements ApplicationRunner {

    @Autowired
    private Scheduler scheduler;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //不存在则新增
        if (!scheduler.checkExists(new JobKey("test","testGroup"))){
            JobDetail detail = JobBuilder.newJob(TestJob.class)
                    .withIdentity("test","testGroup")
                    .withDescription("测试工作任务")
                    .usingJobData("xxxx","ggggg")
                    .build();

            CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                    .withIdentity("test","testGroup")
                    .withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
                    .forJob(detail)
                    .build();

            scheduler.scheduleJob(detail, cronTrigger);
            scheduler.start();
            return;
        }
        Trigger.TriggerState state = scheduler.getTriggerState(new TriggerKey("test","testGroup"));
        log.info("state : {}", state.name());
    }
}
